#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

// 用法：./server
int main(int argc, char const* argv[])
{
    if (3 != argc)
    {
        printf("Usage: %s <ip> <port>",argv[0]);
        return -1;
    }
    
    int socket_fd;
    socket_fd = socket(AF_INET,SOCK_DGRAM,0);
    if (socket_fd==-1)
    {
        perror("socket err\n");
        return -1;
    }
    
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(atoi(argv[2]));
    addr.sin_addr.s_addr=inet_addr(argv[1]);

    if(bind(socket_fd,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        perror("bind err\n");
        close(socket_fd);
        return -1;
    }

    struct sockaddr_in client_addr;
    int addrlen = sizeof(client_addr);   

    char buf[64]={'\0'};     
    while (1)
    {
        memset(buf,0,64);
        ssize_t len=recvfrom(socket_fd,buf,64,0,(struct sockaddr*)&client_addr,&addrlen);
        if (len>0)
        {
            printf("recv data = %s\n",buf);
            //sendto(server_socket,buf,64,0,(struct sockaddr*)&client_addr,addrlen);
        }
        
    }
    close(socket_fd);
    
    return 0;
}